import stringRandom from "string-random";
import { loginInfo } from "../mysql/index.js";
import { Request, Response, NextFunction } from 'express';
import config from "../config/default.js";
import usermag from "../staticeClass/usermag.js";

export default (req: Request, res: Response, next: NextFunction) => {
  const { username, password } = req.body;
  loginInfo(username, password)
    .then((data) => {
      res.status(200);

      if ((data as usermag[]).length > 0) {
        let token = stringRandom(16, { numbers: false });
        config.cookie = token;
        res.cookie('token', token, { signed: true, httpOnly: true, maxAge: 86400000 });

        res.send(JSON.stringify({
          code: "200",
          message: "登录成功！"
        }));
      } else {
        res.send(JSON.stringify({
          code: "404",
          message: "账号或密码错误！"
        }))
      }
    }).catch((e) => {
      console.warn(e);
      res.status(500);
      res.send(JSON.stringify({
        code: "500",
        message: "数据库查询出错！"
      }))
    })
}